<template>
  <a-layout>
    <a-layout-header class="layout-header">
      <a-space>
        <a-button
          type="link"
          style="margin-left: -24px"
          @click="$router.push('/')"
        >
          <template #icon>
            <ArrowLeftOutlined />
          </template>
          <span>返回</span>
        </a-button>
      </a-space>
      <a-space>
        <!-- <a-button
          type="primary"
          :disabled="type === 'code'"
          @click="handelDownload"
        >
          代码下载
        </a-button> -->
        <a-button type="primary" @click="showModal">字段匹配</a-button>
        <a-button type="primary" danger @click="resetWindow">重置代码</a-button>
      </a-space>
    </a-layout-header>
    <a-layout-content class="code-wrapper">
      <CodeEditor
        autoPasteClip
        :type="type"
        v-model:code="code"
        v-model:diffCode="diffCode"
      />
    </a-layout-content>
  </a-layout>
  <ReplaceModal
    v-model:modelValue="replaceModalVisible"
    :metaData="metaData"
    @replaceFieldList="handleReplace"
  />
</template>

<script setup>
import { ref } from "vue";
import { message } from "ant-design-vue";
import { ArrowLeftOutlined } from "@ant-design/icons-vue";

import CodeEditor from "@/components/CodeEditor/index.vue";
import { downloadCode } from "@/utils/index";
import ReplaceModal from "./ReplaceModal.vue";
// import demoCode from "./test/test.vue?raw";
const demoCode=''

const fieldMapReg = /\/\*\*\s*\%fieldMap=([\s\S]+)\%\s*\*\//;
const replaceModalVisible = ref(false);
const metaData = ref([]);
const type = ref("code");
const code = ref(demoCode);
const diffCode = ref("");

function showModal() {
  const result = fieldMapReg.exec(code.value);
  if (!result) {
    return message.warn("没有匹配到元数据，无法替换！");
  }
  metaData.value = JSON.parse(result[1]);
  replaceModalVisible.value = true;
}

function handleReplace(fieldList) {
  let codeStr = code.value;
  for (const field of fieldList) {
    codeStr = codeStr.replaceAll(field.beforeKey, field.afterKey);
  }
  const result = fieldMapReg.exec(codeStr);
  codeStr = codeStr.replace(result[0], "");
  type.value = "diff";
  diffCode.value = codeStr;
}

function handelDownload() {
  downloadCode(diffCode.value, "Diff.vue");
}

function resetWindow() {
  type.value = "code";
  code.value = "";
  diffCode.value = "";
}
</script>

<style lang="less" scoped>
@header-height: 60px;
@border-style:1px solid #ddd;

.ant-layout .ant-layout-header {
  display: flex;
  justify-content: space-between;
  height: @header-height;
  line-height: @header-height;
  background: #fff !important;
  border-bottom: @border-style;
  padding: 0 20px;
  .operate-btn-group {
    height: 100%;
  }
}
.code-wrapper {
  position: relative;
  width: 100vw;
  height: calc(100vh - (@header-height + 10px));
  overflow: hidden;
}

</style>

